<template>
  <el-tabs :value="active" type="card" @tab-remove="removeTab" @tab-change="tabChange">
    <el-tab-pane :closable="item.key != 'home'" :key="item.key" v-for="(item) in tabStore.tabs" :label="item.title"
      :name="item.routeName"></el-tab-pane>
  </el-tabs>
</template>
<script lang="ts" setup>
import { ElTabs, ElTabPane, type TabPaneName } from '~element-plus';
import { useLayoutTabsStore, type TabsInterface } from '@/stores/layoutTabs';
import { computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useKeepLiveStore } from '@/stores/keepLive';
const { push } = useRouter()
const tabStore = useLayoutTabsStore()
const keepLiveStore = useKeepLiveStore()
const active = computed(() => tabStore.active?.routeName)

watch(tabStore, ({ tabs }) => {
  for (const tab of tabs) {
    keepLiveStore.addKeepAlive(tab.routeName, "tabs")
  }
})

function removeTab(key: TabPaneName) {
  const preTab = tabStore.tabs[tabStore.tabs.findIndex(item => item.routeName === key) - 1] // 上一个tab 按钮
  tabStore.closeMultipleTab({ key } as TabsInterface)
  push({ name: preTab.routeName as string, })
}

function tabChange(key: TabPaneName) {
  keepLiveStore.addKeepAlive(key as string, "tabs")
  if (keepLiveStore.isCache) {
    const routes = keepLiveStore.tabToBreadcrumbsMapping[key]
    console.log("mapping", routes, "key", key, keepLiveStore.tabToBreadcrumbsMapping);

    if (!routes || routes.length === 0) {
      push({ name: key as string, })
    } else {
      push({ name: routes[routes.length - 1] })
    }
    return
  }
  push({ name: key as string, })
}
</script>
<style lang="scss" scoped></style>